#!/usr/bin/env python
# Usage: run_test BACKEND_GEN <test>
# BACKEND_GEN: is one of skip_js_exec
# test: is the .sk file in src/tests to test
#
# Environment Variables:
# VERBOSE - show diff in baseline or error output
# UPDATE_BASELINE - update the baseline to the current output and pass the test

from __future__ import print_function

import argparse
import imp
import logging
import os
import shutil
import subprocess
import sys

common = imp.load_source(
    'common',
    os.path.join(os.path.dirname(sys.argv[0]), './runtime/tools/common.py'))

from common import RED, GREEN, NORMAL

logger = logging.getLogger(__name__)


def runtest(args, test, libs):
    test = common.computeRelativePath(test)

    shortBackend = common.getShortBackend()

    profile_args = []
    if args.profile:
        if os.path.exists(args.profile):
            os.remove(args.profile)
        profile_args = ['--profile', args.profile]
    cmd = [args.backend_gen,] + profile_args + [common.prelude(), test] + libs
    if args.sk_standalone:
      cmd += ['--sk-standalone', args.sk_standalone]

    if shortBackend == 'native':
        # Tests tend to be small and should not bother with parallelism.
        cmd += ['--parallel', '1']

    env = os.environ.copy()

    expectError = '/invalid/' in test
    with common.PerfTimer('run_test.RunCommand'):
        result = common.RunCommand(test, cmd, env=env, expectError=expectError)

    if not result.checkReturnCode():
        return False

    if result.report_diff():
        return False

    result.success()
    return True


def main():
    parser = argparse.ArgumentParser(
        description='Run skip compiler tests',
        parents=[common.commonArguments()])
    parser.add_argument('test', nargs='+', help='is the .sk file in src/tests to test')
    args = common.parse_args(parser)

    if args.relative:
        os.chdir(args.relative)

    libs = args.test[:-1]
    result = runtest(args, args.test[-1], libs)
    return 2 * (not result)


if __name__ == '__main__':
    rc = main()
    sys.exit(rc)
